//
//  taskListDetailAdmin.m
//  SQLiteTesting
//
//  Created by kitinat on 2/11/13.
//  Copyright (c) 2013 EGA. All rights reserved.
//
#import "EGAAppDelegate.h"
#import "taskListDetailAdmin.h"

#import "showFileVC.h"

#import "ARC_DB.h"

#import "UIViewController+MJPopupViewController.h"

#import "talkFirstStepVC.h"
#import "EGAEmployeeInfo.h"

#import "EGAUtility.h"

@interface taskListDetailAdmin ()
{
    UIViewController* popoverContent;
    UIView *popoverView;
}

@end

@implementation taskListDetailAdmin

@synthesize DocID;
@synthesize EmpID;


@synthesize wvTaskTraveler;


@synthesize lbTaskDetail1;
@synthesize lbTaskDetail2;
@synthesize lbTaskDetail3;
@synthesize lbTaskDetail4;
@synthesize lbTaskDetail7;
@synthesize lbTaskDetail8;
@synthesize lbTaskDetail9;
@synthesize lbTaskDetail10;




@synthesize btnTalkFirstStep;

@synthesize lbDocName;
@synthesize lbDocSerial;
@synthesize lbDocDate;
@synthesize lbDocRecieveDate;
@synthesize lbIsDueDate;
@synthesize lbIsDueDateColon;



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}










NSArray * arrTaskDetail;


- (void)viewDidLoad
{
    
    [super viewDidLoad];
    
    [self dismissKeyboard];
    
    [self checkRoleManagerForDisableTalkFirstStep];
    
    ARC_DB * DB = [[ARC_DB alloc]init];
    
    if ([DB isHasTaskDetailInDB:DocID] && ![DB internetConnected])
    {
        [self alertNotConnect];
        arrTaskDetail = [DB getTaskDetail:DocID];
        [self setTaskDetail];
        [self loadRequestWebview];

    }
    else
    {
        [self refresh];
    }

    
  
}



#pragma dismisskeyboard
- (void)dismissKeyboard {
    [self globalResignFirstResponder];
}
- (void) globalResignFirstResponder {
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    for (UIView * view in [window subviews]){
        [self globalResignFirstResponderRec:view];
    }
}
- (void) globalResignFirstResponderRec:(UIView*) view {
    if ([view respondsToSelector:@selector(resignFirstResponder)]){
        [view resignFirstResponder];
    }
    for (UIView * subview in [view subviews]){
        [self globalResignFirstResponderRec:subview];
    }
}



-(void)refresh
{
    ARC_DB * DB = [[ARC_DB alloc]init];
    if([DB internetConnected])
    {
        [DB saveTaskDetail:DocID taskUserOrAdmin:@"admin" empID:EmpID];
        arrTaskDetail = [DB getTaskDetail:DocID];
        [self setTaskDetail];
        [self loadRequestWebview];
    }
    else
    {
        [self alertNotConnect];
        [self loadRequestWebview];
    }

}


-(void)loadRequestWebview
{

    NSString *strUrl=[NSString stringWithFormat:@"http://%@Travel.aspx?docID=",serviceUrl];
    NSString *urlAddress =[strUrl stringByAppendingString:DocID];
    
    NSURL *url = [NSURL URLWithString:urlAddress];

    

    
    
    
    
    
    
    
    
    
    //set stored file name
    NSString * storeFileName = [NSString stringWithFormat:@"%@.txt",DocID] ;
    ARC_DB * DB = [[ARC_DB alloc]init];
    //update webview 
    if([DB internetConnected])
    {
        NSString *HTML = [NSString stringWithContentsOfURL: url encoding: NSUTF8StringEncoding error: nil];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:storeFileName];
        [HTML writeToFile:filePath atomically:TRUE encoding:NSUTF8StringEncoding error:NULL];
        [wvTaskTraveler loadHTMLString: HTML baseURL: url];
    }
    //check if file exist or not
    else if([self isHasFileWithSavedFileName:storeFileName])
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:storeFileName];
        NSString *HTML = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
        [wvTaskTraveler loadHTMLString: HTML baseURL: url];
    }
    
    
    
    
}






-(BOOL)isHasFileWithSavedFileName:(NSString*)savedFileName
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:savedFileName];
    
    //if file not exist in document
    if([fileManager fileExistsAtPath:writablePath])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}






-(void)setTaskDetail
{
    NSDictionary*dicForEachRow = [arrTaskDetail objectAtIndex:0];
    lbTaskDetail1.text = [dicForEachRow objectForKey:@"Doc_Register"];
    //lbTaskDetail2.text = [dicForEachRow objectForKey:@"Doc_Subject"];
    //lbTaskDetail3.text = [dicForEachRow objectForKey:@"Description"];
    lbTaskDetail4.text = [dicForEachRow objectForKey:@"Velocity"];
    lbTaskDetail7.text = [dicForEachRow objectForKey:@"Recorder"];
    //lbTaskDetail8.text = [dicForEachRow objectForKey:@"StartDate"];
    //lbTaskDetail9.text = [dicForEachRow objectForKey:@"DueDate"];
    
    
    
    
    
    int len = [[dicForEachRow objectForKey:@"Doc_Subject"] length];
      NSLog(@"len sub%d",len);
    if (len > 60){
        [_btSubject setFrame:CGRectMake(188, 93, 480,50)];
    }
    else
    {
        [_btSubject setFrame:CGRectMake(188, 95, 480,25)];
    }
    if (len<160) {
       // _subImgPop.hidden=YES;
    }
    UILabel *buttonLabel = [[UILabel alloc] initWithFrame:_btSubject.bounds];
    buttonLabel.numberOfLines = 2;
  
     buttonLabel.text =[dicForEachRow objectForKey:@"Doc_Subject"];
   // _btSubject.backgroundColor=[UIColor redColor];
    [buttonLabel setTextColor:[UIColor darkGrayColor]];
    [_btSubject addSubview:buttonLabel];
    [_btSubject bringSubviewToFront:buttonLabel];
    
    int   lenDex = [[dicForEachRow objectForKey:@"Description"] length];
    NSLog(@"len des%d",lenDex);
    if (lenDex > 60){
        [_btDescription setFrame:CGRectMake(188, 140, 480,60)];
    }
    else
    {
        [_btDescription setFrame:CGRectMake(188, 144, 480,25)];
    }
    if (lenDex<160) {
      //  _desImgPop.hidden=YES;
    }
    UILabel *buttonLabelDes  = [[UILabel alloc] initWithFrame:_btDescription.bounds];
    buttonLabelDes.numberOfLines = 2;
   buttonLabelDes.text =[dicForEachRow objectForKey:@"Description"];
     //buttonLabelDes.text =@"yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy";
    [buttonLabelDes setTextColor:[UIColor darkGrayColor]];
    [_btDescription addSubview:buttonLabelDes];
    [_btDescription bringSubviewToFront:buttonLabelDes];
    
    
    lbTaskDetail2.text =[dicForEachRow objectForKey:@"Doc_Subject"];
    lbTaskDetail2.numberOfLines = 2;
    
    lbTaskDetail3.text =[dicForEachRow objectForKey:@"Description"];
    lbTaskDetail3.numberOfLines = 2;

    lbDocSerial.text = [dicForEachRow objectForKey:@"Doc_Serial"];
    EGAUtility * Util = [[EGAUtility alloc]init];
    lbTaskDetail8.text = [Util getDateTh:([dicForEachRow objectForKey:@"StartDate"])];
    lbTaskDetail9.text =[Util getDateTh:([dicForEachRow objectForKey:@"DueDate"])];
    lbDocDate.text= [Util getDateTh:([dicForEachRow objectForKey:@"Doc_Date"])];
    lbDocRecieveDate.text=[Util getDateTh:([dicForEachRow objectForKey:@"Doc_ReceiveDate"])];
    
    
    
    
    NSString * IsDusDate =[dicForEachRow objectForKey:@"IsDueDate"];    if ([IsDusDate isEqualToString:@"0"])
    {
        lbIsDueDateColon.text=@"";
        lbIsDueDate.text=@"";
        lbTaskDetail9.text=@"";
    }
    
    //set doc title
    lbDocName.text = [NSString stringWithFormat:@"[ติดตาม] %@",[dicForEachRow objectForKey:@"Doc_Subject"]];
    
    NSString * taskStatus = [dicForEachRow objectForKey:@"TaskStatus"];
    if ([taskStatus isEqualToString:@"1"])
        lbTaskDetail10.text = @"ยังไม่ดำเนินการ";
    else if ([taskStatus isEqualToString:@"4"])
        lbTaskDetail10.text = @"ดำเนินการเรียบร้อย";
    
    

    //book
    NSArray *arrDocBookBeforeSign_ID    = [[dicForEachRow objectForKey:@"DocBookBeforeSign_ID"] componentsSeparatedByString:@";"];
    NSArray *arrDocBookBeforeSign_Name  = [[dicForEachRow objectForKey:@"DocBookBeforeSign_Name"] componentsSeparatedByString:@";"];
    
    if([arrDocBookBeforeSign_ID count]!=1)
    {
        for(int i = 0; i <= [arrDocBookBeforeSign_ID count]-2 ; i++)
        {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            if (i == 0)
                [button setFrame:CGRectMake(212, 305, 100,25 )];
            else
                [button setFrame:CGRectMake(((i+1)*100)+112, 305, 100, 25 )];
            [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
            
            NSString * strBtnTitle = [NSString stringWithFormat:@" %@  ",arrDocBookBeforeSign_Name[i]];
            [button setTitle:strBtnTitle forState:UIControlStateNormal];
            
            [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
            [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
            button.accessibilityLabel = [NSString stringWithFormat:@"%@|%@",arrDocBookBeforeSign_ID[i],arrDocBookBeforeSign_Name[i]];
            
            //set button image
            NSArray     * arrFileInfo           = [button.accessibilityLabel componentsSeparatedByString:@"|"];
            NSString    * fileID                = arrFileInfo[0];
            NSString    * fileNameAndType       = arrFileInfo[1];
            NSArray     * arrFileNameAndType    = [fileNameAndType componentsSeparatedByString:@"."];
            NSString    * fileType              = arrFileNameAndType[   [arrFileNameAndType count]-1   ];
            NSString    *  storeFileName = [NSString stringWithFormat:@"%@%@.%@",@"task",fileID,fileType];
            UIImage *img ;
            if([self isHasFileWithSavedFileName:storeFileName])
                img = [UIImage imageNamed:@"open.png"];
            else
                img = [UIImage imageNamed:@"save.png"];
            
            [button setImage:img forState:UIControlStateNormal];
            
            button.titleLabel.font = [UIFont systemFontOfSize:13];
            
            [self.view addSubview:button];
            
        }
        
    }
    
    
    //attachment
    NSArray *arrDocAttachment_ID    = [[dicForEachRow objectForKey:@"DocAttachment_ID"] componentsSeparatedByString:@";"];
    NSArray *arrDocAttachment_Name  = [[dicForEachRow objectForKey:@"DocAttachment_Name"] componentsSeparatedByString:@";"];
        
    if([arrDocAttachment_ID count]!=1)
    {
        for(int i = 0; i <= [arrDocAttachment_ID count]-2 ; i++)
        {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            if (i == 0)
                [button setFrame:CGRectMake(212, 279, 100,25 )];
            else
                [button setFrame:CGRectMake(((i+1)*100)+112, 279, 100, 25 )];
            [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
            
            NSString * strBtnTitle = [NSString stringWithFormat:@" %@  ",arrDocAttachment_Name[i]];
            [button setTitle:strBtnTitle forState:UIControlStateNormal];
            
            [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
            [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
            button.accessibilityLabel = [NSString stringWithFormat:@"%@|%@",arrDocAttachment_ID[i],arrDocAttachment_Name[i]];
            
            //set button image
            NSArray     * arrFileInfo           = [button.accessibilityLabel componentsSeparatedByString:@"|"];
            NSString    * fileID                = arrFileInfo[0];
            NSString    * fileNameAndType       = arrFileInfo[1];
            NSArray     * arrFileNameAndType    = [fileNameAndType componentsSeparatedByString:@"."];
            NSString    * fileType              = arrFileNameAndType[   [arrFileNameAndType count]-1   ];
            NSString    *  storeFileName = [NSString stringWithFormat:@"%@%@.%@",@"task",fileID,fileType];
            UIImage *img ;
            if([self isHasFileWithSavedFileName:storeFileName])
                img = [UIImage imageNamed:@"open.png"];
            else 
                img = [UIImage imageNamed:@"save.png"];

            [button setImage:img forState:UIControlStateNormal];
            
            button.titleLabel.font = [UIFont systemFontOfSize:13];
            
            [self.view addSubview:button];
            
        }

    }
}


- (void)buttonPressed:(UIButton *)sender
{
    self.SFVC = [[showFileVC alloc] initWithNibName:@"showFileVC" bundle:nil];
    
    self.SFVC.fileInfo = sender.accessibilityLabel;
    self.SFVC.TalkOrTask = @"task";
    [self presentPopupViewController:self.SFVC animationType:0 popupType:@"showFileTask"];
}

-(void)alertNotConnect
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ไม่สามารถเชื่อมต่อกับเซิฟเวอร์"
                                                    message:@"ทำให้ไม่สามารถอัพเดทข้อมูล"
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
}






- (IBAction)refreshTouch:(id)sender {
    UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    spinner.center = CGPointMake(660, 130);
    spinner.hidesWhenStopped = YES;
    [self.view addSubview:spinner];
    [spinner startAnimating];
    
    
    
    dispatch_queue_t submitTalkSecondQueue = dispatch_queue_create("submitTalkSecond", NULL);
    dispatch_async(submitTalkSecondQueue, ^{
        
        // do our long running process here
        [NSThread sleepForTimeInterval:2];
        
        // do any UI stuff on the main UI thread
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            
            
            [self refresh];

            
            
            
            [spinner stopAnimating];
        });
    });
    dispatch_release(submitTalkSecondQueue);
    
    
    
    
}





- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}








- (IBAction)talkFirstStepTouch:(id)sender {
    talkFirstStepVC *talkFirstVC = [[talkFirstStepVC alloc] initWithNibName:@"talkFirstStepVC" bundle:nil];
    talkFirstVC.DocID = DocID;
    [self presentPopupViewController:talkFirstVC animationType:0 popupType:@"talk"];
}




 





-(EGAAppDelegate*)appDelegate
{
    return  (EGAAppDelegate*)[[UIApplication sharedApplication] delegate];
}
-(void)checkRoleManagerForDisableTalkFirstStep
{
    NSString *RoleName = self.appDelegate.employeeInfo.RoleName;
    if([RoleName isEqualToString:@"manager"])
    {
        btnTalkFirstStep.hidden = YES;
    }
}







- (void)dealloc {
    
    
    
     
    [_btSubject release];
    [_btDescription release];
     
    [_btPopSub release];
    [_btPopDes release];
 
    

    [super dealloc];
}
- (IBAction)btSubClick:(id)sender {
    CGRect popRect ;
    popoverContent = [[UIViewController alloc] init];
      popRect = CGRectMake(123,168,_btSubject.frame.size.width,_btSubject.frame.size.height);
    popoverView = [[UIView alloc] initWithFrame:popRect];
    popoverView.backgroundColor = [UIColor whiteColor];
    popoverContent.view = popoverView;
    popoverContent.contentSizeForViewInPopover = CGSizeMake(500, 150);
    UIPopoverController *desPop = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
    UITextView *stw=[[UITextView alloc] initWithFrame:CGRectMake(10, 10, 500, 150)];
    [stw setTextColor:[UIColor darkGrayColor]];
    stw.backgroundColor = [UIColor clearColor];
    
    
    [popoverView addSubview:stw];
    
    [popoverContent release];
  
    
    stw.font = [UIFont systemFontOfSize:17.0];
     NSDictionary*dicForEachRow = [arrTaskDetail objectAtIndex:0];
     stw.text=[dicForEachRow objectForKey:@"Doc_Subject"];
    [stw setTextColor:[UIColor darkGrayColor]];
    
  //  int len = [[dicForEachRow objectForKey:@"Doc_Subject"] length];
  //  if (len > 160){
        [desPop presentPopoverFromRect:popRect inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
   // }
}
- (IBAction)btDesClick:(id)sender {
    CGRect popRect ;
    popoverContent = [[UIViewController alloc] init];
    popRect = CGRectMake(123,210,_btDescription.frame.size.width,_btDescription.frame.size.height);
    popoverView = [[UIView alloc] initWithFrame:popRect];
    popoverView.backgroundColor = [UIColor whiteColor];
    popoverContent.view = popoverView;
    popoverContent.contentSizeForViewInPopover = CGSizeMake(500, 150);
    UIPopoverController *desPop = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
    UITextView *stw=[[UITextView alloc] initWithFrame:CGRectMake(10, 10, 500, 150)];
    [stw setTextColor:[UIColor darkGrayColor]];
    stw.backgroundColor = [UIColor clearColor];
    
    
    [popoverView addSubview:stw];
    
    [popoverContent release];
   
    
    stw.font = [UIFont systemFontOfSize:17.0];
    NSDictionary*dicForEachRow = [arrTaskDetail objectAtIndex:0];
    stw.text=[dicForEachRow objectForKey:@"Description"];
    [stw setTextColor:[UIColor darkGrayColor]];
    
   // int len = [[dicForEachRow objectForKey:@"Description"] length];
    //if (len > 160){
        [desPop presentPopoverFromRect:popRect inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
  //  }
}
@end
